package com.qmx.smedicinebox.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmx.smedicinebox.constant.Constant;
import com.qmx.smedicinebox.sys.dao.MedicationSituationDao;
import com.qmx.smedicinebox.sys.entity.MedicationPictureEntity;
import com.qmx.smedicinebox.sys.entity.MedicationSituationEntity;
import com.qmx.smedicinebox.sys.entity.MedicineEntity;
import com.qmx.smedicinebox.sys.entity.UserEntity;
import com.qmx.smedicinebox.sys.service.MedicationPictureService;
import com.qmx.smedicinebox.sys.service.MedicationSituationService;
import com.qmx.smedicinebox.sys.service.MedicineService;
import com.qmx.smedicinebox.sys.service.UserService;
import com.qmx.smedicinebox.utils.*;
import com.qmx.smedicinebox.vo.MedicationSituationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("medicationSituationService")
public class MedicationSituationServiceImpl extends ServiceImpl<MedicationSituationDao, MedicationSituationEntity> implements MedicationSituationService {
    @Autowired
    private UserService userService;

    @Autowired
    private DeviceUserRelationServiceImpl deviceUserRelationService;
    @Autowired
    private MedicineService medicineService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MedicationSituationEntity> page = this.page(
                new Query<MedicationSituationEntity>().getPage(params),
                new QueryWrapper<MedicationSituationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R medicationSituationList(Integer userId, String date) {
        QueryWrapper<UserEntity> userWapper = new QueryWrapper<>();
        userWapper.eq("u_id", userId);
        UserEntity one = userService.getOne(userWapper);
        if(Objects.isNull(one)){
            return R.error("未找到相应用户");
        }

        QueryWrapper<MedicationSituationEntity> msWrapper = new QueryWrapper<>();
        msWrapper.eq("s_user",userId);
        List<MedicationSituationEntity> medicationSituationEntities = this.baseMapper.selectList(msWrapper);

        List<MedicationSituationVo> collect = medicationSituationEntities.stream().filter(item -> {
            //匹配相应日期
            String s = DateTimeUtil.splitDate(item.getSDate(),Constant.HYPHEN);
            return s.equals(date);
        }).map(item -> {

            MedicationSituationVo medicationSituationVo = new MedicationSituationVo();
            medicationSituationVo.setId(item.getSId());

            String datetime = DateTimeUtil.splitDate(item.getSDate(),Constant.SLASH);
            medicationSituationVo.setDate(DateTimeUtil.removeLeadingZeros(datetime, Constant.SLASH));
            medicationSituationVo.setUnit(item.getSUnit());
            medicationSituationVo.setTime(DateTimeUtil.splitTimeNotSecond(item.getSDate(),Constant.COLON));
            medicationSituationVo.setDrugId(item.getSMedicine());
            medicationSituationVo.setAll_number(item.getSDosing());
            medicationSituationVo.setUserId(item.getSUser());
            medicationSituationVo.setImage(item.getSPic());
            return medicationSituationVo;

        }).collect(Collectors.toList());


        return R.ok().put("date",collect);
    }

    @Override
    public R save(MedicationSituationVo mSVo) {
        MedicationSituationEntity mSEntity = new MedicationSituationEntity();

        mSEntity.setSPic(mSVo.getImage());
        mSEntity.setSDosing(mSVo.getAll_number());
        mSEntity.setSUnit(mSVo.getUnit());
        mSEntity.setSMedicine(mSVo.getDrugId());
        mSEntity.setSUser(mSVo.getUserId());

        String date = DateTimeUtil.addLeadingZeros(mSVo.getDate(),Constant.HYPHEN);
        String time = mSVo.getTime();
        String datetime = date + " " + time;
        Date dateTime = DateTimeUtil.TransformStringToDateTimeNotSecond(datetime,Constant.SLASH,Constant.COLON);
        mSEntity.setSDate(dateTime);
        mSEntity.setSTime(dateTime);

        int insert = this.baseMapper.insertMs(mSEntity);
        if(insert == 0){
            return R.error("保存失败");
        }

        return R.ok();
    }

//    @Override
//    public boolean insertNewRecord(Integer deviceId, String link) {
//        return false;
//    }

//    @Override
//    public boolean insertNewRecord(Integer deviceId, String link) {
//        MedicationSituationEntity medicationSituationEntity = new MedicationSituationEntity();
//        Date date = new Date();
//
//        medicationSituationEntity.setSDate(date);
//        medicationSituationEntity.setSTime(date);
//        medicationSituationEntity.setSPic(link);
//
//        List<MedicineEntity> list = medicineService.list();
//        int i = RandomUtil.randomInt(0, list.size() - 1);
//        MedicineEntity medicine = list.get(i);
//        medicationSituationEntity.setSDosing(4);
//
//        medicationSituationEntity.setSMedicine(medicine.getMId());
//        medicationSituationEntity.setSUnit(medicine.getMUnit());
//        medicationSituationEntity.setSUser(userId);
//
//        int insert = this.baseMapper.baseInsert(medicationSituationEntity);
//        if(insert == 0){
//            return false;
//        }
//        return true;
//    }

    @Override
    public void insertNewRecord(Integer deviceId, String link, MedicineEntity medicine) {
        MedicationSituationEntity medicationSituationEntity = new MedicationSituationEntity();
        Date date = new Date();
        Integer userId = deviceUserRelationService.getUserId(deviceId);

        medicationSituationEntity.setSDate(date);
        medicationSituationEntity.setSTime(date);
        medicationSituationEntity.setSPic(link);
        medicationSituationEntity.setSDosing(4);
        medicationSituationEntity.setSMedicine(medicine.getMId());
        medicationSituationEntity.setSUnit(medicine.getMUnit());
        medicationSituationEntity.setSUser(userId);

        int insert = this.baseMapper.baseInsert(medicationSituationEntity);
    }

    @Override
    public boolean determineSave(Integer medicineId) {
        QueryWrapper<MedicationSituationEntity> wrapper = new QueryWrapper<>();

        // 获取当前时间
        Date now = new Date();

        // 计算五分钟前的时间
        Date fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
        System.out.println(fiveMinutesAgo);

        wrapper.ge("s_date", fiveMinutesAgo).le("s_date", now);
        // 执行查询
        List<MedicationSituationEntity> medicationSituationEntities = this.baseMapper.selectList(wrapper);

        System.out.println(medicationSituationEntities);

        for(int i=0;i<medicationSituationEntities.size();i++){
            MedicationSituationEntity medicationSituationEntity = medicationSituationEntities.get(i);
            Integer sMedicine = medicationSituationEntity.getSMedicine();
            if(sMedicine.equals(medicineId)) return false;
        }

        return true;
    }

}